"""
    批量处理，循环预测
"""

import numpy as np
import pandas as pd

import joblib

from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, MinMaxScaler

from common.functions import *


def get_data():
    # 读取数据集
    data = pd.read_csv("../data/train.csv")

    # 2. 划分数据集和测试集
    X = data.drop("label",axis=1)
    Y = data['label']

    x_train,x_test,y_train,y_test = train_test_split(X,Y,test_size=0.3)

    # 3. 归一化处理
    preprocessor = MinMaxScaler()
    x_train = preprocessor.fit_transform(x_train)
    x_test = preprocessor.transform(x_test)

    return x_test,y_test


# 初始化神经网络(加载参数)
def init_network():
    network = joblib.load("../data/nn_sample")
    return network

# 前向传播
def forward(network, x):
    W1,W2,W3 = network['W1'],network['W2'],network['W3']
    b1,b2,b3 = network['b1'] ,network['b2'],network['b3']

    a1 = np.dot(x,W1) + b1
    z1 = sigmoid_function(a1)

    a2 = np.dot(z1,W2) +b2
    z2 = sigmoid_function(a2)

    a3 = np.dot(z2,W3) +b3
    # 多分类，使用 softmax 作为激活函数
    y = softmax_function_v2(a3)
    return y


if __name__ == '__main__':
    # 1. 获取数据
    x,y = get_data()

    # 2. 创建模型
    network = init_network()

    # 3.定义一些参数
    n = x.shape[0]
    batch_size = 100
    accuracy_cnt = 0

    for i  in range(0,n,batch_size):
        print("batch start ====================>")
        # 1.取出一批需要处理的数据
        x_train = x[i:i+batch_size]
        # 2. 批量处理
        y_probs = forward(network, x_train)
        print(y_probs)

        # 3.转换成分类标签
        y_pred = np.argmax(y_probs, axis=1)
        print(y_pred)
        # 4. 累积预测正确的个数
        accuracy_cnt = accuracy_cnt + np.sum(y_pred == y[i:i+batch_size])
        print("batch start <====================")
    print(f"准确率是:{accuracy_cnt/n}")
